#!/usr/bin/env node

const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

// 读取 package.json 文件
const packageJsonPath = path.join(__dirname, "..", "package.json");
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));

// 获取当前版本
const currentVersion = packageJson.version;
console.log(`当前版本: ${currentVersion}`);

// 解析版本号
const [major, minor, patch] = currentVersion.split(".").map(Number);

// 询问要更新的版本类型
rl.question(
  "请选择要更新的版本类型 (1: patch, 2: minor, 3: major): ",
  (answer) => {
    let newVersion;
    let versionType;

    switch (answer.trim()) {
      case "3":
        newVersion = `${major + 1}.0.0`;
        versionType = "major";
        break;
      case "2":
        newVersion = `${major}.${minor + 1}.0`;
        versionType = "minor";
        break;
      case "1":
      default:
        newVersion = `${major}.${minor}.${patch + 1}`;
        versionType = "patch";
        break;
    }

    console.log(`新版本: ${newVersion}`);

    rl.question(`确认更新版本至 ${newVersion} 并发布? (y/n): `, (confirm) => {
      if (confirm.toLowerCase() !== "y") {
        console.log("已取消发布");
        rl.close();
        return;
      }

      // 更新 package.json 文件
      packageJson.version = newVersion;
      fs.writeFileSync(
        packageJsonPath,
        JSON.stringify(packageJson, null, 4) + "\n"
      );

      // 如果存在 package-lock.json，也更新它
      const packageLockPath = path.join(__dirname, "..", "package-lock.json");
      if (fs.existsSync(packageLockPath)) {
        const packageLock = JSON.parse(
          fs.readFileSync(packageLockPath, "utf8")
        );
        packageLock.version = newVersion;
        fs.writeFileSync(
          packageLockPath,
          JSON.stringify(packageLock, null, 2) + "\n"
        );
      }

      console.log("版本已更新，开始构建...");

      try {
        // 构建应用
        console.log("正在构建 Windows 版本...");
        execSync("npm run dist:win", { stdio: "inherit" });
        console.log(
          `构建完成! 安装包位于: dist_electron/微信机器人 Setup ${newVersion}.exe`
        );

        // 如果是 Git 仓库，创建提交和标签
        try {
          // 检查是否是 Git 仓库
          execSync("git rev-parse --is-inside-work-tree", { stdio: "ignore" });

          // 添加更改的文件
          execSync("git add package.json");
          if (fs.existsSync(packageLockPath)) {
            execSync("git add package-lock.json");
          }

          // 创建提交
          execSync(`git commit -m "chore: 版本更新至 ${newVersion}"`);

          // 创建标签
          execSync(`git tag v${newVersion}`);

          console.log(`已创建 Git 提交和标签 v${newVersion}`);

          // 询问是否推送到远程仓库
          rl.question("是否推送到远程仓库? (y/n): ", (pushConfirm) => {
            if (pushConfirm.toLowerCase() === "y") {
              try {
                console.log("正在推送到远程仓库...");
                execSync("git push", { stdio: "inherit" });
                execSync("git push --tags", { stdio: "inherit" });
                console.log("推送完成");
              } catch (pushError) {
                console.error("推送失败:", pushError);
              }
            }

            console.log(`发布完成! 版本: ${newVersion}`);
            rl.close();
          });
        } catch (gitError) {
          console.log("跳过 Git 操作，可能不是 Git 仓库或发生错误");
          console.log(`发布完成! 版本: ${newVersion}`);
          rl.close();
        }
      } catch (buildError) {
        console.error("构建失败:", buildError);
        rl.close();
        process.exit(1);
      }
    });
  }
);
